package com.xuetang9.t9.hotel.mapper.sql.impl;

import com.xuetang9.t9.hotel.mapper.condition.ICondition;
import com.xuetang9.t9.hotel.mapper.condition.impl.ReservationCondition;
import com.xuetang9.t9.hotel.mapper.sql.IMapperSql;
import org.apache.ibatis.jdbc.SQL;

import java.util.Map;

/**
 * @author Pang
 */
public class ReservationMapperSql implements IMapperSql {

    @Override
    public String selectByAll(Map map){
        ICondition key = (ICondition) map.get("key");
        return getSql("*",key,true);
    }

    @Override
    public String selectByCount(Map map){
        ICondition key = (ICondition) map.get("key");
        return getSql("COUNT(*)",key,false);
    }

    private String getSql(String head,ICondition condition,boolean isPage){
        SQL sql = new SQL();
        sql.SELECT(head).FROM("g_reservation");
        if(isNull(condition)) {
            return sql.toString();
        }
        ReservationCondition reservationCondition = null;
        if(condition instanceof ReservationCondition){
            reservationCondition = (ReservationCondition)condition;
        }else{
            throw new RuntimeException("condition type Don't match");
        }
        if(isNull(reservationCondition)) {
            return sql.toString();
        }
        if(!isNull(reservationCondition.getReservationTime())){
            sql.WHERE(SelectTimeSql.getSql(reservationCondition.getReservationTime(),"reservation_date"));
        }
        if(!isNull(reservationCondition.getEtaTiem())){
            sql.WHERE(SelectTimeSql.getSql(reservationCondition.getEtaTiem(),"arrive_date"));
        }
        if(!isNull(reservationCondition.getReservationStart())){
            sql.WHERE("reservation_state = "+reservationCondition.getReservationStart());
        }
        if (!isNull(reservationCondition.getReservationType())){
            sql.WHERE("reservation_type = "+reservationCondition.getReservationType());
        }
        if (!isNull(reservationCondition.getName())){
            sql.WHERE("guest_name LIKE '%"+reservationCondition.getName()+"%'");
        }
        if (!isNull(reservationCondition.getPhone())){
            sql.WHERE("guest_phone LIKE '%"+reservationCondition.getPhone()+"%'");
        }
        if(reservationCondition.judge()  && isPage){
            sql.LIMIT(reservationCondition.getCurrPage()+","+reservationCondition.getPageSize());
        }
        return sql.toString();
    }


    private boolean isNull(Object value){
        return value == null || value.equals("")?true:false;
    }


}
